<template>
  <div class="live-container">
    <div class="player_warpper">
      <div class="left">
        <PlayerHeader :stream="streamData.data" :anchor="anchorData.data" />
        <div class="player">
          <div class="player-controls">
            <div class="fullscreen-btn" @click="toggleFullScreen">
              <i :class="isFullScreen ? 'icon-exit-fullscreen' : 'icon-fullscreen'"></i>
            </div>
          </div>
          
          <iframe
            v-show="streamData.data?.playAddr?.ori_m3u8"
            id="iframePlayer"
            ref="videoIframe"
            class="player_iframe"
            allowfullscreen="allowfullscreen"
            mozallowfullscreen="mozallowfullscreen"
            msallowfullscreen="msallowfullscreen"
            oallowfullscreen="oallowfullscreen"
            webkitallowfullscreen="webkitallowfullscreen"
            src="https://video.dunduiby.com/?isLive=1&isRobot=0&isLogined=0&isHideCtrl=0&isNeedDanmaku=0&isForceHls=0&isTwitch=0&isNeedTheaterMode=1&isNeedWaterMask=false&waterMaskImg=jingyu&isPIP=false"
          ></iframe>
          <div v-show="!streamData.data?.playAddr?.ori_m3u8" class="offline-status">
            <span>{{ loading ? '正在加载直播间中...' : '主播未开播' }}</span>
          </div>
        </div>
        <div class="gift">
          <Gift />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import PlayerHeader from './player-header.vue'
import Gift from './gift.vue'
import Chat from './chat.vue'
import { defineProps, ref, reactive, watch, onMounted, onUnmounted } from 'vue'

const props = defineProps({
  match: Object,
  streams: Object,
  anchor: Object,
  chatId: String,
  loading: {
    type: Boolean,
    default: false
  }
})
let matchData = reactive({ data: {} })
let streamData = reactive({ data: {} })
let anchorData = reactive({ data: {} })
let video_iframe_timer = null
const isFullScreen = ref(false)
const videoIframe = ref(null)

const initPlayer = (playAddr) => {
  console.log(playAddr, 'playAddr')
  const data = {
    playAddr: {
      flv: playAddr.ori_flv,
      m3u8: playAddr.ori_m3u8,
      DPlayerID: 'iFrame_Player'
    }
  }
  console.log(data, 'data')
  video_iframe_timer = setInterval(function () {
    sendMessageToIframe(data)
  }, 1000)
}

const sendMessageToIframe = (data) => {
  var iframe = document.getElementById('iframePlayer')
  // console.log(iframe, 'iframe')
  if (iframe) {
    iframe.contentWindow.postMessage(data, '*')
    iframe.addEventListener('load', function () {
      console.log(iframe)
      iframe.contentWindow.postMessage(data, '*')
    })
  } else {
    console.log('iframe not found')
  }
}

window.addEventListener('message', function (event) {
  if (event.data.msg === 'playing') {
    if (video_iframe_timer) {
      clearInterval(video_iframe_timer)
      video_iframe_timer = null
    }
  }
})

watch(
  () => props.match,
  (newProps, oldProps) => {
    matchData.data = newProps
  }
)

watch(
  () => props.streams,
  (newProps, oldProps) => {
    console.log(newProps, 'newProps')
    streamData.data = newProps
    if (newProps.playAddr?.ori_m3u8 && newProps.playAddr?.ori_flv) {
      initPlayer(newProps.playAddr)
    }
  }
)

watch(
  () => props.anchor,
  (newProps, oldProps) => {
    anchorData.data = newProps
  }
)

const toggleFullScreen = async () => {
  try {
    const iframe = videoIframe.value
    const playerContainer = iframe?.closest('.player')
    
    if (!isFullScreen.value) {
      if (iframe) {
        // 尝试让 iframe 全屏
        if (iframe.requestFullscreen) {
          await iframe.requestFullscreen()
        } else if (iframe.webkitRequestFullscreen) {
          await iframe.webkitRequestFullscreen()
        } else if (iframe.mozRequestFullScreen) {
          await iframe.mozRequestFullScreen()
        } else if (iframe.msRequestFullscreen) {
          await iframe.msRequestFullscreen()
        }
      } else if (playerContainer) {
        // 如果 iframe 全屏失败，尝试让容器全屏
        if (playerContainer.requestFullscreen) {
          await playerContainer.requestFullscreen()
        } else if (playerContainer.webkitRequestFullscreen) {
          await playerContainer.webkitRequestFullscreen()
        } else if (playerContainer.mozRequestFullScreen) {
          await playerContainer.mozRequestFullScreen()
        } else if (playerContainer.msRequestFullscreen) {
          await playerContainer.msRequestFullscreen()
        }
      }
    } else {
      if (document.exitFullscreen) {
        await document.exitFullscreen()
      } else if (document.webkitExitFullscreen) {
        await document.webkitExitFullscreen()
      } else if (document.mozCancelFullScreen) {
        await document.mozCancelFullScreen()
      } else if (document.msExitFullscreen) {
        await document.msExitFullscreen()
      }
    }
  } catch (error) {
    console.error('全屏切换失败:', error)
  }
}

// 监听全屏状态变化
const handleFullScreenChange = () => {
  isFullScreen.value = !!(
    document.fullscreenElement ||
    document.webkitFullscreenElement ||
    document.mozFullScreenElement ||
    document.msFullscreenElement
  )
}

onMounted(() => {
  if (video_iframe_timer) {
    clearInterval(video_iframe_timer)
  }
  document.addEventListener('fullscreenchange', handleFullScreenChange)
  document.addEventListener('webkitfullscreenchange', handleFullScreenChange)
  document.addEventListener('mozfullscreenchange', handleFullScreenChange)
  document.addEventListener('MSFullscreenChange', handleFullScreenChange)
})

onUnmounted(() => {
  if (video_iframe_timer) {
    clearInterval(video_iframe_timer)
    video_iframe_timer = null
  }
  document.removeEventListener('fullscreenchange', handleFullScreenChange)
  document.removeEventListener('webkitfullscreenchange', handleFullScreenChange)
  document.removeEventListener('mozfullscreenchange', handleFullScreenChange)
  document.removeEventListener('MSFullscreenChange', handleFullScreenChange)
})
</script>

<style scoped lang="scss">
.live-container {
}
.player_warpper {
  display: flex;
  justify-content: space-between;

  .left {
    background: #ffffff;
    border-radius: 20px 20px 20px 20px;
    width: 860px;
    .player {
      height: 600px;
      width: 100%;
      position: relative;
      border: 1px solid #e5e5e5;
      background: #333;

      .player-controls {
        position: absolute;
        bottom: 20px;
        right: 20px;
        z-index: 10;
        display: flex;
        gap: 10px;
        padding: 10px;
        // background: rgba(0, 0, 0, 0.5);
        border-radius: 4px;
        opacity: 0;
        transition: opacity 0.3s;
      }
      
      &:hover .player-controls {
        // opacity: 1;
      }

      .fullscreen-btn {
        cursor: pointer;
        color: #fff;
        padding: 5px;
        transition: all 0.3s;
        
        &:hover {
          color: #16b13a;
        }

        i {
          font-size: 24px;
        }
      }

      &:fullscreen {
        padding: 0;
        // background: #000;
        
        // .player_iframe {
        //   width: 100vw;
        //   height: 100vh;
        // }
      }

      .player_iframe {
        background: #333;
        height: 100%;
        width: 100%;
        outline: none;
        border: none;
      }

      .offline-status {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        font-size: 16px;
        color: #666;
        width: 200px;
        text-align: center;
        height: 60px;
        line-height: 60px;
        border: 1px solid #666;
        border-radius: 10px;

        // 添加加载中的动画效果
        &.loading {
          span::after {
            content: '';
            animation: dots 1.5s infinite;
          }
        }
      }
    }
  }
}

@keyframes dots {
  0%,
  20% {
    content: '';
  }
  40% {
    content: '.';
  }
  60% {
    content: '..';
  }
  80% {
    content: '...';
  }
  100% {
    content: '';
  }
}

:deep(.player:fullscreen) {
  width: 100vw !important;
  height: 100vh !important;
  padding: 0 !important;
  background: #000 !important;
  
  .player_iframe {
    width: 100vw !important;
    height: 100vh !important;
  }
}
</style>
